package com.rbcs.base.project.webapp;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.rbcs.base.item.service.ItemManager;
import com.rbcs.base.model.Item;
import com.rbcs.base.model.ProjectType;
import com.rbcs.base.project.service.ProjectTypeManager;
import com.systop.core.ApplicationException;
import com.systop.core.webapp.struts2.action.DefaultCrudAction;

@SuppressWarnings("serial")
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ProjectTypeAction extends
		DefaultCrudAction<ProjectType, ProjectTypeManager> {

	@Autowired
	private ItemManager itemManager;

	private Integer[] selectedItemIds;

	private List<Item> unSelectedItems;

	/**
	 * 项目分类
	 */
	public String index() {
		String hql = "from ProjectType p order by p.code";
		getRequest().setAttribute(EC_DATA_NAME, getManager().query(hql));
		return INDEX;
	}

	/**
	 * 项目类别编辑,准备未选择类别
	 */
	public String edit() {
		unSelectedItems = itemManager.getUnSelectedByProjectType();
		return INPUT;
	}

	/**
	 * 保存项目类别
	 */
	public String save() {
		try {
			if (getModel().getId() != null) {//如果是修改，每次都将关联的科目删除，再保存
				for (Item item : getModel().getItems()) {
					item.setProjectType(null);
					itemManager.save(item);
				}
			}
			getManager().save(getModel());
			if (selectedItemIds != null) { //将已选择科目关联保存
				for (Integer id : selectedItemIds) {
					Item item = itemManager.get(id);
					item.setProjectType(getModel());
					itemManager.save(item);
				}
			}
			return SUCCESS;
		} catch (ApplicationException e) {
			addActionError(e.getMessage());
			return INPUT;
		}
	}

	/**
	 * 删除项目类别
	 */
	public String remove() {
		if (getModel() != null && getModel().getId() != null) {
			long projectCount = getManager().getProjectCounts(getModel());
			if (projectCount > 0) {//判断是否有项目关联
				throw new ApplicationException("类别【" + getModel().getName()
						+ "】包含" + projectCount + "个项目，禁止删除！");
			}
			List<Item> items = getModel().getItems();
			if (items != null && !items.isEmpty()){//断开科目关联
				for(Item i : items){
					i.setProjectType(null);
					itemManager.save(i);
				}
			}
			getManager().remove(getModel());

		}
		return SUCCESS;
	}

	public Integer[] getSelectedItemIds() {
		return selectedItemIds;
	}

	public void setSelectedItemIds(Integer[] selectedItemIds) {
		this.selectedItemIds = selectedItemIds;
	}

	public List<Item> getUnSelectedItems() {
		return unSelectedItems;
	}

	public void setUnSelectedItems(List<Item> unSelectedItems) {
		this.unSelectedItems = unSelectedItems;
	}

}
